package java;

public class Question7 {
    public static void main(String[] args) {
        int num = myReverse(-2147483412);
        System.out.println(num);
    }

    private static int myReverse(int num) {
        String numStr = String.valueOf(num);
        String reversedNum;
        if (numStr.startsWith("-")){
            reversedNum ="-" + reverse(numStr.substring(1));
            System.out.println(reversedNum);
        }else {
            reversedNum = reverse(numStr);
            System.out.println(reversedNum);
        }
        if (isLegal(reversedNum)){
            return Integer.parseInt(reversedNum);
        }
        return 0;
    }

    private static boolean isLegal(String reversedNum) {
        String maxStr = String.valueOf(Integer.MAX_VALUE);
        String minStr = String.valueOf(Integer.MIN_VALUE);
        String temp = maxStr;
        if (reversedNum.startsWith("-")){
            temp = minStr;
        }
        if (reversedNum.length() < temp.length()){
            return true;
        }else if (reversedNum.length() > temp.length()){
            return false;
        }else {
            for (int i = 0 ;i < reversedNum.length();i ++){
                if (reversedNum.charAt(i) < temp.charAt(i)){
                    return true;
                }
                if (reversedNum.charAt(i) > temp.charAt(i)){
                    return false;
                }
            }
        }
        return true;
    }

    private static String reverse(String numStr) {
        StringBuffer stringBuffer = new StringBuffer(numStr);
        stringBuffer = stringBuffer.reverse();
        for (int i = 0;i < stringBuffer.length();i ++){
            if (stringBuffer.length() > 1){
                if (stringBuffer.charAt(0) == '0'){
                    stringBuffer.deleteCharAt(0);
                }else {
                    break;
                }
            }
        }
        return stringBuffer.toString();
    }

}

